import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { Line, Pie, Bar } from 'react-chartjs-2';
import { Chart as ChartJS, ArcElement, Tooltip, Legend, CategoryScale, LinearScale, PointElement, LineElement, BarElement, Title } from 'chart.js';
import { FaUsers, FaDatabase, FaExclamationTriangle, FaInfoCircle } from 'react-icons/fa';
import '../styles/Dashboard.css';

// 注册ChartJS组件
ChartJS.register(ArcElement, Tooltip, Legend, CategoryScale, LinearScale, PointElement, LineElement, BarElement, Title);

const Dashboard = () => {
  const [dashboardData, setDashboardData] = useState({
    sourceCount: 0,
    personnelCount: 0,
    changesCount: 0,
    errorCount: 0,
    recentChanges: [],
    changesByType: { labels: [], data: [] },
    changesByDate: { labels: [], data: [] },
    changesByOrganization: { labels: [], data: [] }
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        setLoading(true);

        // 获取采集源数量
        const sourcesRes = await axios.get('/api/sources');
        const sourceCount = sourcesRes.data.length;
        const errorCount = sourcesRes.data.filter(source => source.status === 'error').length;

        // 获取人员数量
        const personnelRes = await axios.get('/api/personnel', {
          params: { limit: 1 }
        });
        const personnelCount = personnelRes.data.pagination.total;

        // 获取最近变更
        const recentChangesRes = await axios.get('/api/personnel/changes/recent', {
          params: { days: 7, limit: 5 }
        });
        const recentChanges = recentChangesRes.data;

        // 获取变更统计
        const statsRes = await axios.get('/api/changelog/stats/summary', {
          params: { days: 30 }
        });
        const stats = statsRes.data;

        // 处理变更类型数据
        const changesByType = {
          labels: stats.changesByType.map(item => getChangeTypeLabel(item._id)),
          data: stats.changesByType.map(item => item.count)
        };

        // 处理按日期的变更数据
        const changesByDate = {
          labels: stats.changesByDate.map(item => item._id),
          data: stats.changesByDate.map(item => item.count)
        };

        // 处理按组织的变更数据
        const changesByOrganization = {
          labels: stats.changesByOrganization.map(item => item._id),
          data: stats.changesByOrganization.map(item => item.count)
        };

        setDashboardData({
          sourceCount,
          personnelCount,
          changesCount: recentChanges.length,
          errorCount,
          recentChanges,
          changesByType,
          changesByDate,
          changesByOrganization
        });

        setError(null);
      } catch (err) {
        console.error('获取仪表盘数据失败:', err);
        setError('获取仪表盘数据失败，请稍后再试');
      } finally {
        setLoading(false);
      }
    };

    fetchDashboardData();
  }, []);

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (error) {
    return <div className="error">{error}</div>;
  }

  return (
    <div className="dashboard">
      <h1>系统仪表盘</h1>

      {/* 统计卡片 */}
      <div className="stat-cards">
        <div className="stat-card">
          <div className="stat-icon">
            <FaDatabase />
          </div>
          <div className="stat-content">
            <h3>采集源</h3>
            <p className="stat-value">{dashboardData.sourceCount}</p>
            <Link to="/sources">查看详情</Link>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon">
            <FaUsers />
          </div>
          <div className="stat-content">
            <h3>人员信息</h3>
            <p className="stat-value">{dashboardData.personnelCount}</p>
            <Link to="/personnel">查看详情</Link>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon">
            <FaInfoCircle />
          </div>
          <div className="stat-content">
            <h3>最近变更</h3>
            <p className="stat-value">{dashboardData.changesCount}</p>
            <Link to="/changelog">查看详情</Link>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon">
            <FaExclamationTriangle />
          </div>
          <div className="stat-content">
            <h3>错误源</h3>
            <p className="stat-value">{dashboardData.errorCount}</p>
            <Link to="/sources">查看详情</Link>
          </div>
        </div>
      </div>

      {/* 图表区域 */}
      <div className="dashboard-charts">
        {/* 按类型的变更 */}
        <div className="chart-container">
          <h3>按类型的变更</h3>
          <div className="chart">
            <Pie
              data={{
                labels: dashboardData.changesByType.labels,
                datasets: [
                  {
                    data: dashboardData.changesByType.data,
                    backgroundColor: [
                      'rgba(75, 192, 192, 0.6)',
                      'rgba(255, 159, 64, 0.6)',
                      'rgba(255, 99, 132, 0.6)',
                    ],
                    borderColor: [
                      'rgba(75, 192, 192, 1)',
                      'rgba(255, 159, 64, 1)',
                      'rgba(255, 99, 132, 1)',
                    ],
                    borderWidth: 1,
                  },
                ],
              }}
              options={{
                responsive: true,
                plugins: {
                  legend: {
                    position: 'bottom',
                  },
                },
              }}
            />
          </div>
        </div>

        {/* 按日期的变更 */}
        <div className="chart-container">
          <h3>最近30天的变更趋势</h3>
          <div className="chart">
            <Line
              data={{
                labels: dashboardData.changesByDate.labels,
                datasets: [
                  {
                    label: '变更数量',
                    data: dashboardData.changesByDate.data,
                    fill: false,
                    backgroundColor: 'rgba(54, 162, 235, 0.6)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    tension: 0.1,
                  },
                ],
              }}
              options={{
                responsive: true,
                scales: {
                  y: {
                    beginAtZero: true,
                  },
                },
              }}
            />
          </div>
        </div>

        {/* 按组织的变更 */}
        <div className="chart-container">
          <h3>按组织的变更</h3>
          <div className="chart">
            <Bar
              data={{
                labels: dashboardData.changesByOrganization.labels,
                datasets: [
                  {
                    label: '变更数量',
                    data: dashboardData.changesByOrganization.data,
                    backgroundColor: 'rgba(153, 102, 255, 0.6)',
                    borderColor: 'rgba(153, 102, 255, 1)',
                    borderWidth: 1,
                  },
                ],
              }}
              options={{
                responsive: true,
                scales: {
                  y: {
                    beginAtZero: true,
                  },
                },
              }}
            />
          </div>
        </div>
      </div>

      {/* 最近变更列表 */}
      <div className="recent-changes">
        <h3>最近变更</h3>
        {dashboardData.recentChanges.length > 0 ? (
          <table className="changes-table">
            <thead>
              <tr>
                <th>人员</th>
                <th>组织</th>
                <th>变更类型</th>
                <th>时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {dashboardData.recentChanges.map((change) => (
                <tr key={change._id}>
                  <td>{change.personnelId?.name || '未知'}</td>
                  <td>{change.personnelId?.organization || '未知'}</td>
                  <td>{getChangeTypeLabel(change.changeType)}</td>
                  <td>{new Date(change.timestamp).toLocaleString()}</td>
                  <td>
                    <Link to={`/personnel/${change.personnelId?._id}`}>查看详情</Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <p>暂无最近变更</p>
        )}
      </div>
    </div>
  );
};

// 变更类型标签
const getChangeTypeLabel = (type) => {
  const typeMap = {
    'new': '新增',
    'updated': '更新',
    'removed': '移除'
  };
  
  return typeMap[type] || type;
};

export default Dashboard; 